<?php
session_start();
	//retrieving user id by session
$member_id = $_SESSION['member_id'];
	//Connect to the database

include ("functions.php");
$con = mysql_connect("localhost", "root", "");


if (!$con) {
    die('Could not connect:' . mysql_error());
}
mysql_select_db("mydb", $con);

	//check if the conference id  and the clicked letter are sent from the previouse page
if (isset($_POST['conference_id'])&&isset($_POST['letter'])) {  
		//retrieving conference id from previous page 
    $conference_id = intval($_POST['conference_id']);
		// check if the page recieve the letter sent to it from the letter link and save this letter in a variable
    $clicked_letter = $_POST['letter']; 
		
	$page_name = "http://localhost:1234/ConfO/inviteOrganizers.php";
		// query that gets the number of member whose last names start with the letter clicked
	$count =  mysql_query("Select distinct m.member_id, first_name, last_name FROM member m, member_privileges Where m.last_name LIKE '$clicked_letter%' 
            AND m.member_id != '$member_id' AND ((m.member_id = member_privileges.member_id) OR ( m.member_id  NOT IN (Select distinct m.member_id  FROM member_privileges,member m where m.member_id = member_privileges.member_id)) )") or die(mysql_error());
		//count the records in the previous query
	$t = mysql_num_rows($count);
		// save the number of member in a variable
	$total_items = $t;
	$limit= 10;
	$page= (isset($_GET["page"]))? $_GET["page"] : 1;

		//Set defaults if: there is no selected page or non numerical 
	if((!$page) || (is_numeric($page) == false)) {
		$page = 1;}
		
		//calculate the total number of pages needed
	$total_pages = ceil($total_items / $limit);

			// query that gets the id, first and last names of member whose last names start with the letter clicked, in ascending order
	    $members_list = mysql_query("Select distinct m.member_id, first_name, last_name 
            FROM member m, member_privileges 
            Where m.last_name LIKE '$clicked_letter%' 
            AND m.member_id != '$member_id' 
            AND ((m.member_id = member_privileges.member_id) 
            OR ( m.member_id  NOT IN (Select distinct m.member_id  
            FROM member_privileges,member m where m.member_id = member_privileges.member_id)) ) 
            ORDER BY last_name ASC") or die(mysql_error());
			

		//count the number of records of the previouse query
	$no_row = mysql_num_rows($members_list);
		// if there are no records resulted from the query, display a message
	if($no_row == 0) die("No matches met your criteria.");
		// a counter that its value is added to the check box and dropdown list for every member in the list to keep track of their ids to know later which of them checked to get the id of its member
    $i = 0;
		// loops on each member in the list by making every row in the selected table in an array
    while ($line = mysql_fetch_assoc($members_list)) { 
	
			// get all committees that are in this conference
        $committees_inconference = mysql_query("Select c.committee_id, c.committee_name From committees c, conference_committee s
											WHERE c.committee_id = s.committee_id AND s.conference_id = '$conference_id'")
											or die(mysql_error());
			// get number of rows
        $rows = mysql_num_rows($committees_inconference); 
       
       		// print the name of each member 
			//generate check box with the id of its member_id and when checked it calls the function that enables the dropdown list
			// generate disabled dropdown list also with the value of its the member id and an id which is the counter (its number in the list)
        echo '<input type="checkbox" name="members[]" class="' . $line['member_id'] . '" value="' . $line['member_id'] . '" onClick="enable(this, ' . $i . ')"> ' . $line['first_name'] . ' ' . $line['last_name'] . '
               <select class="'. $line['member_id'] . '" value="" id="Committees' . $i . '" name=\"Committees[]" onClick="commID(this)" disabled="disabled">';
		// incrementing the counter
        $i++; 
			// loop for populating the dropdown list
        for ($j = 0; $j < $rows; $j++) { 
				//get the committee name with a counter which is considered its id, it comes second in the array
            $commName = mysql_result($committees_inconference, $j, 1);
				//get the committee id with a counter which is considered its id, it comes first in the array
            $commId = mysql_result($committees_inconference, $j, 0); 
				// add the committee name to the dropdown list, committee id is its value
            echo '<option value="' . $commId . '">' . $commName . '</option>'; 
        }

        echo '</select></br>';
    }
		// set the value of the previous page
	$prev_page = $page - 1;
		// if the current page is not the first page 
	if($prev_page >= 1) {
			// display a previous link that takes the value of the previous page
		echo("<b><<</b> <a href=$page_name?page=$prev_page>
		<b>Prev.</b></a>");
	}
		// generate the numerical paging links 
	for($a = 1; $a <= $total_pages; $a++){
		if($a == $page) {
			echo("<b> $a</b> | "); //no link
		}
		else {
				echo("<a href=$page_name?page=$a> $a</a> | ");
			}
	}
		//set the value of the next page
	$next_page = $page + 1;
		// if the current page is not the last page 
	if($next_page <= $total_pages) {
		// display a next link that takes the value of the next page
	echo ("<a href=$page_name?page=$next_page><b>Next</b></a> > > <br><br>");
	}
echo'<button name="Done" onClick ="javascript:InvitationDone();">Done</button>';
}
		

    // when the Done button is clicked after the member are chosen as well the committees they's assigned to,
	// make sure the two arrays of the check boxes and drop down lists along with the conference id is sent from invitations page InvitationsDone method
    if (isset($_POST['member_ids']) && isset($_POST['committees'])&&isset($_POST['conference_id'])) {
			//save the conference id in a variable
        $conference_id = intval($_POST['conference_id']);
				// it loops on the check boxes to check which of them are checked
            for ($j = 0; $j < count($_POST['member_ids']); $j++) {  
					//gets each member id which is the value of the check box
                $rec_id = $_POST['member_ids'][$j];  
					// gets the committee id which is the value of the of the clicked committee name
                $com_Id = $_POST['committees'][$j]; 
					// sanitizing the variable that will be inserted in the database
                $reciever_id = mysql_real_escape_string($rec_id);
					// sanitizing the variable that will be inserted in the database
                $committee_Id = mysql_real_escape_string($com_Id);
					//insert into table request an empty invitation 
                $get_lastid = mysql_query("INSERT INTO request(request) VALUES (null)") or die(mysql_error()); 
					// checking if the empty request is inserted 
                if ($get_lastid) { 
						// get the last request id inserted in the table request in the database
                    $l_id = mysql_insert_id(); 
						//sanitizing the variable that will be inserted in the database
                    $last_id = mysql_real_escape_string($l_id); 
                }
                // get the name of the selected committee
                $committee_name = mysql_query("SELECT committee_name FROM committees WHERE committee_id = '$committee_Id'") or die(mysql_error());
                // put the result in an array to retrieve the required field
                $c_name = mysql_fetch_assoc($committee_name);
                //retireve the required field from the array which is the committee name
                $com_name = $c_name['committee_name'];
                // get the first and last name of the invitation receiever
                $reciever_name = mysql_query("SELECT first_name, last_name FROM member WHERE member_id = '$reciever_id'") or die(mysql_error());
                // put the result in an array to retrieve the required field
                $name = mysql_fetch_assoc($reciever_name);
                //retireve the required fields from the array which are the first and last name
                $f_name = $name['first_name'];
                $l_name = $name['last_name'];
                // query to check if the member is already invited, so it check if his data is already in the database
                $if_already_invited = mysql_query("SELECT member_id2,conference_id,type FROM member_request_member m, request_committee r
													WHERE m.request_id = r.request_id AND r.committee_id = '$committee_Id' AND member_id2='$reciever_id' AND
													conference_id ='$conference_id' AND type= 'O'") or die(mysql_error());

                if (mysql_num_rows($if_already_invited)) {
                    // error message if the member is already invited, that says that the member is already invited to this conference
                    $message = "$f_name" . " " . "$l_name" . " " . 'was already invited to' . " " . "$com_name" . " " . 'in this conference';
                    // print the message
                    echo $message
                    ?></br><?
                } else {
                    //insert the ids of the invitor, invited member, conference and type of request whether for reviewers or organizers in the request table to be rejected or accepted by those members
                    mysql_query("INSERT INTO member_request_member(member_id1, member_id2, conference_id,request_id,type) VALUES('$member_id','$reciever_id','$conference_id','$last_id','O')") or die(mysql_error());
                    //insert this request id and the committee that the member is invited to be an organizer in the database
                    mysql_query("INSERT INTO request_committee(request_id, committee_id) VALUES('$last_id','$committee_Id')") or die('No committee is selected' . mysql_error());
                    //get the name of the conference
                    $get_conference_id = mysql_query("SELECT long_name from Conference where conference_id ='$conference_id'") or die(mysql_error());
                    // put the result in an array to retrieve the required field
                    $row = mysql_fetch_assoc($get_conference_id);
                    //retireve the required field from the array which the conference name
                    $conference_name = $row['long_name'];
                    // the request text 
                    $request_text = 'ConfO would like to request your organizing services in the ' . "$conference_name" . ' conference. You can review the conference details in the conference page.';
                    // calling the function of sending requests to the chosen members
                    sendRequest($_POST['member_ids'], $request_text, $conference_id, $l_id);
					echo '<script>',
						'alert("Your request(s) has been successfully sent!");',
						'</script>';
					
                }



                // omar kahil
            
        }
    }
	else {
	echo '<script>',
            'alert("No members are checked");',
            '</script>';
			}


// I will take them from the session that has been chosen in the checklist
function sendRequest($requestUserID, $request_text, $confid, $l_id) {

    $members = $_POST ['member_ids'];

    for ($j = 0; $j < count($_POST ['member_ids']); $j++) {
        $requestUserID = $members[$j];
        $O = 'O';
  $check = mysql_query("SELECT member_id2,conference_id,type FROM member_request_member WHERE member_id2='$requestUserID'
            AND conference_id ='$confid' AND type= '$O'")
                or die(mysql_error());

        if (mysql_num_rows($check)==0) {
            mysql_query("UPDATE request SET request = '$request_text' where request_id = '$l_id'") or die('can not insert request' . mysql_error()); //insert the request message into the table request
}
}
}
mysql_close($con);


?>
            

